package echat.future.cn.echat.my.view;

import android.app.Dialog;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.R;
import echat.future.cn.echat.databinding.ActivityEditeAuthInfoBinding;
import echat.future.cn.echat.my.api.PutObjectSamplesApi;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.bean.BaseVo;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.MeHelper;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.my.weight.Navagation.AdapterNavagation;
import echat.future.cn.echat.my.weight.Navagation.IBaseNavagation;
import echat.future.cn.echat.my.weight.ProgrossDialog;
import echat.future.cn.echat.my.weight.dialog.DatePickerDialogFragment;
import echat.future.cn.echat.my.weight.dialog.StringDialog;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class EditeAuthInfoActivity extends BaseActivity<ActivityEditeAuthInfoBinding> implements TextWatcher {

    private Dialog heightDialog;

    private Dialog weight;
    private Dialog sex;

    private List<String> selectTags = new ArrayList<>();

    @Override
    public int layoutId() {
        return R.layout.activity_edite_auth_info;
    }

    @Override
    public IBaseNavagation navagation() {
        return new AdapterNavagation(this).setTitle("编辑认证资料", 16, R.color.white).setBack(R.drawable.btn_back).setNavagationBackgroudColor(R.color.color_161823);

    }

    @Override
    public void initView() {
        bind.weight.setOnClickListener(v -> showWeight());
        bind.height.setOnClickListener(v -> showHeightDialog());
        bind.brithday.setOnClickListener(v -> showBirthday());
        bind.sex.setOnClickListener(v -> showSex());
        bind.xingxiang.setOnClickListener(v -> {
            startActivityForResult(new Intent(EditeAuthInfoActivity.this, SetTagActivity.class), 10);
        });
        bind.llTag.setOnClickListener(v -> startActivityForResult(new Intent(EditeAuthInfoActivity.this, SetTagActivity.class), 10));
        bind.sign.setOnClickListener(v -> {
            startActivityForResult(new Intent(EditeAuthInfoActivity.this, EditSignActivity.class).putExtra("title", "个性签名"), 20);
        });

        bind.confirm.setOnClickListener(v -> {
            sendHttp();
        });

        bind.nickName.addTextChangedListener(this);
        bind.phone.addTextChangedListener(this);
        bind.city.addTextChangedListener(this);
        bind.job.addTextChangedListener(this);
        onOverInput();
    }

    private void showHeightDialog() {
        if (heightDialog == null) {
            heightDialog = new StringDialog.Builder(this)
                    .title("选择身高")
                    .datas(MeHelper.getHeight())
                    .comfirmListener(title -> {
                        bind.height.setText(title);
                        onOverInput();
                    })
                    .builder();
        }
        heightDialog.show();
    }


    private void showWeight() {
        if (weight == null) {
            weight = new StringDialog.Builder(this)
                    .title("选择体重").datas(MeHelper.getWeight())
                    .comfirmListener(title -> {
                                bind.weight.setText(title);
                                onOverInput();
                            }
                    )
                    .builder();
        }
        weight.show();
    }


    private void showSex() {
        if (sex == null) {
            sex = new StringDialog.Builder(this)
                    .title("选择性别").datas(MeHelper.getSex())
                    .comfirmListener(title -> {
                                bind.sex.setText(title);
                                onOverInput();
                            }
                    )
                    .builder();
        }
        sex.show();
    }

    public void showBirthday() {
        DatePickerDialogFragment datePickerDialogFragment = new DatePickerDialogFragment();
        datePickerDialogFragment.setOnDateChooseListener((year, month, day) -> {
            bind.brithday.setText(String.format("%02d-%02d-%02d", year, month, day));
            onOverInput();
        });
        datePickerDialogFragment.show(getSupportFragmentManager(), "DatePickerDialogFragment");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == RESULT_OK) {
            showTags(data.getStringArrayListExtra("data"), data.getStringExtra("ids"));
        }

        if (requestCode == 20 && resultCode == RESULT_OK) {
            bind.sign.setText(data.getStringExtra("data"));
        }
        bind.picSelectorView.onActivityResult(requestCode, resultCode, data);
        onOverInput();
    }

    private void showTags(List<String> tags, String ids) {
        bind.xingxiang.setVisibility(View.GONE);
        bind.llTag.setVisibility(View.VISIBLE);
        bind.llTag.setContentDescription(ids == null ? "" : ids);
        selectTags.clear();
        selectTags.addAll(tags);
        bind.tag1.setText(tags.get(0));
        bind.tag2.setText(tags.get(1));
    }

    /**
     * 是否完全输入
     */
    private void onOverInput() {
        bind.confirm.setEnabled(false);

        if (selectTags.size() == 0) {
            return;
        }
        if (bind.nickName.getText().toString().equals("")) {
            return;
        }
        if (bind.phone.getText().toString().equals("")) {
            return;
        }
        if (bind.height.getText().toString().equals("")) {
            return;
        }

        if (bind.weight.getText().toString().equals("")) {
            return;
        }

        if (bind.brithday.getText().toString().equals("")) {
            return;
        }

        if (bind.city.getText().toString().equals("")) {
            return;
        }
        if (bind.job.getText().toString().equals("")) {
            return;
        }
        if (bind.sign.getText().toString().equals("")) {
            return;
        }
        if (bind.sex.getText().toString().equals("")) {
            return;
        }
        bind.confirm.setEnabled(true);
    }

    ProgrossDialog progrossDialog;

    private void sendHttp() {
        List<String> files = new ArrayList();
        for (int i = 0; i < bind.picSelectorView.getSelectorUrls().size(); i++) {
            if (bind.picSelectorView.getSelectorUrls().get(i).getItemType() == 0) {
                continue;
            }
            files.add(bind.picSelectorView.getSelectorUrls().get(i).getImg());
        }
        if (files.size() == 0) {
            toast("至少需要一张图片");
            return;
        }

        PutObjectSamplesApi.upLoadFils(files)
                .flatMap(strings -> HttpUtilsRequst.retrofitClient.create(UserApi.class).authZhubo(
                        UserHelper.getToken(),
                        bind.phone.getText().toString(),
                        bind.nickName.getText().toString(),
                        bind.height.getText().toString(),
                        bind.weight.getText().toString(),
                        bind.brithday.getText().toString(),
                        bind.city.getText().toString(),
                        bind.job.getText().toString(),
                        bind.llTag.getContentDescription().toString(),
                        bind.sign.getText().toString(),
                        bind.sex.getText().toString(),
                        new Gson().toJson(strings)
                ))
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseVo<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (progrossDialog == null) {
                            progrossDialog = new ProgrossDialog(EditeAuthInfoActivity.this);
                        }
                        progrossDialog.show();
                    }

                    @Override
                    public void onNext(BaseVo<String> tBaseVo) {
                        if (tBaseVo.getCode() == 1) {
                            startActivity(new Intent(EditeAuthInfoActivity.this, AuthenticationZhuboActivity.class).
                                    putExtra("type", AuthenticationZhuboActivity.TYPE_PROGROSS));
                            finish();
                        } else {
                            toast(tBaseVo.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        progrossDialog.dismiss();
                    }

                    @Override
                    public void onComplete() {
                        progrossDialog.dismiss();
                    }
                });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        onOverInput();
    }
}
